<!DOCTYPE html>
<html lang="en" class="app">
<head>
  <meta charset="utf-8" />
  <title>轮播图片</title>
  <meta imageTitle="description" content="app, web app, responsive, admin dashboard, admin, flat, flat ui, ui kit, off screen nav" />
  <meta imageTitle="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
  <link rel="stylesheet" href="${base}/rs/css/bootstrap.4.0.css" type="text/css" />
  <link rel="stylesheet" href="${base}/rs/css/app.v2.css" type="text/css" />
  <link rel="stylesheet" href="${base}/rs/css/font-awesome1.min.css" type="text/css" />
  <link rel="stylesheet" href="${base}/rs/css/bootstrap-table.css" type="text/css" />
  <link rel="stylesheet" href="${base}/rs/ueditor/css/editor-style.css" type="text/css" />
  <link rel="stylesheet" href="${base}/rs/plugins/lightbox/lightbox.min.css" type="text/css" />
  <style>
    * {margin:0; padding:0;list-style: none}

    #ul1 {width:660px; position:relative; margin:10px auto;height: 380px;}
    #ul1 li {width:200px; height:150px; float:left; list-style:none; margin:10px;}
    #ul1 li:hover{ border-color: #9a9fa4; box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.85);}
    #ul1 .active{ border:1px dashed red;}
    .button-bar{ width:120px;margin: 0 auto;}
  </style>
  <script type="text/javascript" src="${base}/rs/js/move.js"></script>
  <script>
      function show() {
          var oUl= document.getElementById("ul1");
          var aLi = oUl.getElementsByTagName("li");

          var disX = 0;
          var disY = 0;
          var minZindex = 1;
          var aPos =[];
          for(var i=0;i<aLi.length;i++){
              var t = aLi[i].offsetTop;
              var l = aLi[i].offsetLeft;
              aLi[i].style.top = t+"px";
              aLi[i].style.left = l+"px";
              aPos[i] = {left:l,top:t};
              aLi[i].index = i;
          }
          for(var i=0;i<aLi.length;i++){
              aLi[i].style.position = "absolute";
              aLi[i].style.margin = 0;
              setDrag(aLi[i]);
          }
          //拖拽
          function setDrag(obj){
              obj.onmouseover = function(){
                  obj.style.cursor = "move";
              }
              obj.onmousedown = function(event){
                  var scrollTop = document.documentElement.scrollTop||document.body.scrollTop;
                  var scrollLeft = document.documentElement.scrollLeft||document.body.scrollLeft;
                  obj.style.zIndex = minZindex++;
                  //当鼠标按下时计算鼠标与拖拽对象的距离
                  disX = event.clientX +scrollLeft-obj.offsetLeft;
                  disY = event.clientY +scrollTop-obj.offsetTop;
                  document.onmousemove=function(event){
                      //当鼠标拖动时计算div的位置
                      var l = event.clientX -disX +scrollLeft;
                      var t = event.clientY -disY + scrollTop;
                      obj.style.left = l + "px";
                      obj.style.top = t + "px";
                    /*for(var i=0;i<aLi.length;i++){
                     aLi[i].className = "";
                     if(obj==aLi[i])continue;//如果是自己则跳过自己不加红色虚线
                     if(colTest(obj,aLi[i])){
                     aLi[i].className = "active";
                     }
                     }*/
                      for(var i=0;i<aLi.length;i++){
                          aLi[i].className = "";
                      }
                      var oNear = findMin(obj);
                      if(oNear){
                          oNear.className = "active";
                      }
                  }
                  document.onmouseup = function(){
                      document.onmousemove = null;//当鼠标弹起时移出移动事件
                      document.onmouseup = null;//移出up事件，清空内存
                      //检测是否普碰上，在交换位置
                      var oNear = findMin(obj);
                      if(oNear){
                          oNear.className = "";
                          oNear.style.zIndex = minZindex++;
                          obj.style.zIndex = minZindex++;

                          startMove(oNear,aPos[obj.index]);
                          startMove(obj,aPos[oNear.index]);
                          //交换index
                          oNear.index += obj.index;
                          obj.index = oNear.index - obj.index;
                          oNear.index = oNear.index - obj.index;

                      }else{
                          startMove(obj,aPos[obj.index]);
                      }
                  }
                  clearInterval(obj.timer);
                  return false;//低版本出现禁止符号
              }
          }
          //碰撞检测
          function colTest(obj1,obj2){
              var t1 = obj1.offsetTop;
              var r1 = obj1.offsetWidth+obj1.offsetLeft;
              var b1 = obj1.offsetHeight+obj1.offsetTop;
              var l1 = obj1.offsetLeft;

              var t2 = obj2.offsetTop;
              var r2 = obj2.offsetWidth+obj2.offsetLeft;
              var b2 = obj2.offsetHeight+obj2.offsetTop;
              var l2 = obj2.offsetLeft;

              if(t1>b2||r1<l2||b1<t2||l1>r2){
                  return false;
              }else{
                  return true;
              }
          }
          //勾股定理求距离
          function getDis(obj1,obj2){
              var a = obj1.offsetLeft-obj2.offsetLeft;
              var b = obj1.offsetTop-obj2.offsetTop;
              return Math.sqrt(Math.pow(a,2)+Math.pow(b,2));
          }
          //找到距离最近的
          function findMin(obj){
              var minDis = 999999999;
              var minIndex = -1;
              for(var i=0;i<aLi.length;i++){
                  if(obj==aLi[i])continue;
                  if(colTest(obj,aLi[i])){
                      var dis = getDis(obj,aLi[i]);
                      if(dis<minDis){
                          minDis = dis;
                          minIndex = i;
                      }
                  }
              }
              if(minIndex==-1){
                  return null;
              }else{
                  return aLi[minIndex];
              }
          }
      }
  </script>
</head>

<body>
<section class="vbox">
  <section class="scrollable padder">
    <!-- ${headTitle} -->
    <div class="m-b-md">
      <h3 class="m-b-none"></h3>
    </div>
    <section class="panel panel-default">
      <header class="panel-heading font-bold">查询条件</header>
      <div class="panel-body col-lg-12">
        <form class="form-inline col-lg-12" role="form">
          <label class="control-label" for="imageTitle" STYLE="line-height: 34px;">标题</label>
          <div class="control-label m-l">
            <input type="text" class="form-control"  id="imageTitle" placeholder="请输入标题">
          </div>
          <button type="button" id="SelectEntity" class="btn btn-default m-l-lg" >搜索</button>
          <a href="javaScript:void(0);" id="addEntity" class="btn btn-success m-l" data-toggle="modal">新增</a>
          <a href="javaScript:void(0);" id="sortEntity" class="btn btn-success m-l" data-toggle="modal">排序</a>
        </form>
      </div>
    </section>

    <div id="toolbar" class="btn-group">
      <button type="button" class="btn btn-default delete"><i class="fa fa-trash"></i>&nbsp;删除</button>
      <button type="button" class="btn btn-default stop"><i class="fa fa-toggle-off"></i>&nbsp;状态</button>
    </div>
    <table class="table table-striped b-t b-light text-sm" id="table">
    </table>
  </section>
</section>

<!-- 轮播图片排序 -->
<div class="block-content-content" id="tong" style="min-height: 100px !important;padding-top:30px;display: none">
      <ul id="ul1">
      </ul>
    <div class="button-bar">
      <button type="button" class="btn btn-default" data-dismiss="modal" id="cancel" >关闭</button>
      <button type="button" class="btn btn-primary save" id="save" >保存</button>
    </div>

</div>

<script type="text/javascript" src="${base}/rs/plugins/lightbox/lightbox-plus-jquery.min.js"></script>
<script src="${base}/rs/js/jquery-3.2.0.min.js"></script>
<script src="${base}/rs/js/layer/layer.js"></script>
<script src="${base}/rs/js/layer/commont.js"></script>
<script src="${base}/rs/js/bootstrap.4.0.js"></script>
<script src="${base}/rs/js/bootstrap-table.js"></script>
<script src="${base}/rs/js/bootstrap-table-zh-CN.js"></script>
<script type="text/javascript" src="${base}/rs/ueditor/js/editor.js"></script>

<script>
    jQuery.noConflict();
</script>

<script type="text/javascript">
    (function(){
        var $table = jQuery('#table');
        var actionEvents = {
            'click .edit': function (e, value, row, index) {
                var url="${base}/msgBanner/SelectEntity?bannerId="+row.bannerId;
                window.location.href=url;
            },
            'click .remove': function (e, value, row, index) {
                layer.confirm("是否删除",{icon:4}, function(){
                    deletemsgBanner(row.bannerId);
                });
            }
        };

        $(function(){
            initTable();

            /** 查询 */
            jQuery("#SelectEntity").on("click", function(e){
                var imageTitle=$("#imageTitle").val();
                $table.bootstrapTable("refresh",{query:{imageTitle: imageTitle}});
            });

            /** 新增 */
            jQuery("#addEntity").click(function () {
                window.location.href="${base}/msgBanner/SelectEntity"
            });

            /** 排序 */
            jQuery("#sortEntity").click(function () {
                var selections = $table.bootstrapTable("getSelections");
                if (selections.length === 0 ) {
                    layer.msg('请选择图片作为首页！', {icon: 0,time: 3*1000});
                    return false;
                }
                var flag=true;
                jQuery.each(selections,function(i,data){
                    if (data.status === '2'){
                        //alert(1);
                        flag=false;
                        return ;
                    }
                });
                if (!flag){
                    layer.msg('请选择启用的图片作为首页！', {icon: 0,time: 3*1000});
                    return false;
                }

                var by = function(name,minor){
                    return function(o,p){
                        var a,b;
                        if(o && p && typeof o === 'object' && typeof p ==='object'){
                            a = o[name];
                            b = p[name];
                            if(a === b){
                                return typeof minor === 'function' ? minor(o,p):0;
                            }
                            if(typeof a === typeof b){
                                return a < b ? -1:1;
                            }
                            return typeof a < typeof b ? -1 : 1;
                        }
                    }
                }

                layer.open({
                    type: 1,
                    title: false,
                    closeBtn: 0,
                    area: ['800px', '500px'],
                    shadeClose: true,
                    content:  $('#tong'),
                    success:function (layero, index) {
                        var oUl= document.getElementById("ul1");
                        var oLis='';
                        jQuery.each(selections,function(i,data){
                            var oLi="<li id='"+data.bannerId+"' ><img src='"+data.imageUrl+"' width='200' height='150'/></li>"
                            oLis+=oLi;
                        });
                        oUl.innerHTML=oLis;
                        show();
                        $("#cancel").click(function(){
                            layer.closeAll('page');
                        });
                        $("#save").click(function (layero,index) {
                            var oUl= document.getElementById("ul1");
                            var aLi = oUl.getElementsByTagName("li");
                            var aPos =[];
                            for(var i=0;i<aLi.length;i++){
                                var t = aLi[i].style.top;
                                var l = aLi[i].style.left;
                                var idv=aLi[i].getAttribute("id");
                                aPos[i]={top:t.replace("px",""),left:l.replace("px",""),id:idv};
                            }
                            aPos=aPos.sort(by('top',by('left')))

                            //alert(aPos[0].id);
                            var ids=[] ;
                            for (var i = 0; i < aPos.length; i++) {
                                ids.push(aPos[i].id);
                            }
                            $.ajax({
                                type: "POST",
                                url: "/msgBanner/sortEntity?ids="+ids,
                                dataType: "json",
                                success: function(result){
                                    if(1==result.returnInfo.state){
                                        showLayerAlert("操作成功");
                                        var url="${base}/rs/msgBanner/listPage";
                                        window.location.href=url;

                                    }else{
                                        showLayerAlert(result.returnInfo.errorMsg);
                                    }
                                },
                                error: function(result){
                                    showLayerAlert(result);
                                }
                            });
                        });
                    }
                });
            });

            /** 删除操作 */
            jQuery("#toolbar").find(".delete").on("click", function(){
                var selections = $table.bootstrapTable("getSelections");
                if (selections.length === 0) {
                    layer.msg('未选中行', {icon: 0,time: 3*1000});
                    return;
                }
                layer.confirm("是否删除",{icon:4}, function(){
                    var ids = [];
                    jQuery.each(selections,function(i,data){
                        ids.push(data.bannerId);
                    });
                    deletemsgBanner(ids.join(","));
                });
            });

            /** 停用操作 */
            $("#toolbar").find(".stop").on("click", function(){
                var selections = $table.bootstrapTable("getSelections");
                if (selections.length === 0) {
                    layer.msg('未选中行', {icon: 0,time: 3*1000});
                    return;
                }
                layer.confirm("是否停用/启用",{icon:4}, function(){
                    var ids = [];
                    jQuery.each(selections,function(i,data){
                        ids.push(data.bannerId+":"+data.status);
                    });
                    stopBanner(ids.join(","));
                });
            });
        });
        /** 初始化表格数据 */
        function initTable() {
            $table.bootstrapTable({
                method: 'post',
                url: '/msgBanner/JsonList',
                striped: true,     //使表格带有条纹
                pagination: true, //在表格底部显示分页工具栏
                pageSize: 10,
                pageNumber: 1,
                pageList: [10, 20, 50, 100, 200, 500],
                idField: "departid",  //标识哪个字段为id主键
                sidePagination: "server",//表格分页的位置
                contentType: "application/x-www-form-urlencoded", //解决POST提交问题
                queryParams:queryParams,
                onLoadSuccess:function (data) {
                    if (data.total==0){
                        //layer.msg('未查询到数据', {icon: 6,time: 3*1000});
                        $table.bootstrapTable("removeAll");
                    }
                }, //参数
                queryParamsType: "limit", //参数格式,发送标准的RESTFul类型的参数请求
                toolbar: "#toolbar", //设置工具栏的Id或者class
                columns: [{
                    checkbox:true,
                    title: '全选',
                    width:'5%',
                    align:'center; line-height:40px',

                },  {
                    title: '序号',
                    width:'5%',
                    align:'center; line-height:40px',
                    formatter: function (value, row, index) {
                        return index+1;
                    }
                },{
                    field: 'imageTitle',
                    width:'30%',
                    title: '标题',
                    align:'center; line-height:40px',
                }, {
                    field: 'status',
                    width:'10%',
                    title: '简介',
                    align:'center; line-height:40px',
                    formatter: function (value, row, index) {
                        if(value == "1"){
                            return "启用";
                        }else{
                            return "未启用";
                        }
                    }
                } , {
                    field: 'imageUrl',
                    title: '封面图片',
                    width:'5%',
                    align: 'center;line-height:40px',
                    formatter: function (value, row, index) {
                        var aUrl=value.replace('_NEW','');
                        return "<a class='example-image-link' href='"+aUrl+"' data-lightbox='example-"+(index+1)+"'><img class='example-image' src='"+value+"' style='width: 40px; height: 40px;'/>";
                    }
                } , {
                    field: 'action',
                    title: '操作',
                    width:'10%',
                    align:'center; line-height:40px',
                    formatter: actionFormatter,
                    events: actionEvents
                }], //列
                silent: true,  //刷新事件必须设置
                formatLoadingMessage: function () {
                    return "请稍等，正在加载中...";
                },
                formatNoMatches: function () {  //没有匹配的结果
                    return '无符合条件的记录';
                },
                onLoadError: function (data) {
                    $('#table').bootstrapTable('removeAll');
                },
            });
        }
      /*封装查询参数*/
        function queryParams(params) {
            var imageTitle=$("#imageTitle").val();
            var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
                pageSize: params.limit,   //页面大小
                pageNum: params.offset,  //页码
                imageTitle: imageTitle
            };
            return temp;
        }
        /**
         *  table列的操作
         */
        function actionFormatter(value, row, index) {
            return [
                '<a href="javaScript:void(0);" class="edit"  data-toggle="class">修改</a> ' +
                '&nbsp;&nbsp;'+
                '<a href="javaScript:void(0);" class="remove" data-toggle="class">删除</a>'
            ].join('');
        }

        /**
         * 删除
         */
        function deletemsgBanner(value){
            jQuery.ajax({
                type: "delete",
                url: "/msgBanner/DeleteEntity?ids="+value,
                success: function(result){
                    if(1==result.returnInfo.state){
                        showLayerAlert("删除成功！");
                    }else{
                        showLayerAlert(result.returnInfo.errorMsg);
                    }
                },
                error: function(result){
                    $table.bootstrapTable("refresh");
                    layer.msg(result.state, {icon: 6,time: 3*1000});
                }
            });
        }

        /**
         * 选择停用
         * @param value
         */
        function stopBanner(value) {
            jQuery.ajax({
                type: "post",
                url: "/msgBanner/stopEntity?ids="+value,
                success: function(result){
                    if(1==result.returnInfo.state){
                        showLayerAlert("停用/启用成功！");
                    }else{
                        showLayerAlert(result.returnInfo.errorMsg);
                    }
                },
                error: function(result){
                    $table.bootstrapTable("refresh");
                    layer.msg(result.state, {icon: 6,time: 3*1000});
                }
            });
        }
    })(jQuery);

    //需要重写
    function showLayerAlert(content){
        layer.open({
            type: 1
            ,title: "操作提示"
            ,offset: "auto" //具体配置参考：http://www.layui.com/doc/modules/layer.html#offset
            ,id: 'LAY_demo_auto' //防止重复弹出
            ,content: '<div style="padding: 20px 100px;">'+ content +'</div>'
            ,btn: "确定"
            ,btnAlign: 'c' //按钮居中
            ,shade: 0 //不显示遮罩
            ,yes: function(){
                jQuery("#table").bootstrapTable("refresh");
                layer.closeAll();
            }
        });
    }

</script>
</body>
</html>
